package hn.cch.grammar.io;

import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 字节流
 */
public class InputOutputDemo {


    @Test
    public void testFile() {

        String content = "line1\nline2";
        String dir = "src/main/resources/io/InputOutput";
        File file = new File(dir);
        File f1 = new File(file, "f1.txt");
        try (FileOutputStream fileOutputStream = new FileOutputStream(f1)) {
            fileOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
            fileOutputStream.flush();

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        byte[] byteArray = new byte[1024];
        int size = 0;

        try (FileInputStream fileInputStream = new FileInputStream(f1)) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while (-1 != (size = fileInputStream.read(byteArray))) {
                byteArrayOutputStream.write(byteArray, 0, size);
            }
            System.out.println(new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }

}
